package org.xdq.练习1;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        List<int[]> list = new ArrayList<>();

        for(int i=0;i<10;i++){
            int[] arr = new int[(int)(Math.random()*10+3)];
            for(int k = 0;k<arr.length;k++){
                arr[k]=(int)(Math.random()*20);
            }
            list.add(arr);
        }

        int sum = 0;
        for(int[] arr : list){
            for(int m : arr){
                sum+=m;
            }
        }
        System.out.println("sum="+sum);

        Vector<Integer> vector = new Vector<>();//共享数据区




//        new Thread("总和线程"){
//            @Override
//            public void run() {
//
//                while(vector.size() < list.size()){
//                    try {
//                        Thread.sleep(10);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//                int s = 0;
//                for(int n : vector){
//                    s+=n;
//                    System.out.println(Thread.currentThread().getName()+"=====>"+n);
//                }
//                System.out.println("总和："+s);
//
//
//            }
//        }.start();



        for(int i=0;i<list.size();i++){

            int[] arr = list.get(i);

            new Thread(()->{
                int s = 0;
                for(int k = 0;k<arr.length;k++){
                    s+=arr[k];
                    System.out.println(Thread.currentThread().getName()+"=====>"+arr[k]);
                    Thread.yield();
                }
                vector.add(s);

            },"线程"+i).start();
        }



        FutureTask<Integer> task = new FutureTask<Integer>(()->{
            while(vector.size() < list.size()){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            int s = 0;
            for(int n : vector){
                s+=n;
            }
            return s;
        });

        new Thread(task).start();
        System.out.println(task.get());


    }


}
